<script setup>
import editCrf from './editCrf.vue';
import { EditPen, CloseBold, ArrowLeftBold, CircleCheck, Search } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { findObject } from '@smallwei/avue';
import draggable from 'vuedraggable';
import goBack from './goBack.vue';
import option from '@/option/phase/phase';
import { treeWithCrf, addToProcessLibrary, processLibraryTreeWithCrf } from '@/api/group/group';
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  phaseSort,
  phaseCrfSort,
} from '@/api/phase/phase';
import { ref, reactive, computed, onMounted, defineEmits, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
const store = useStore();
const router = useRouter();
const route = useRoute();
const routerQuery = ref({});
routerQuery.value = route.query;
const emit = defineEmits();
const form = ref({});
const isPhaseAdd = ref(false);
let phaseTitle = ref('');
let getPhaseOption = ref({ ...option });
const phaseOption = ref({});
let getGroupId = routerQuery.value.groupId;
const flowList = ref([]);
let crfSelect = ref(null);
let crfSelectOptions = ref([]);
let phaseAddDialogWidth = ref(800);
let editCrfRef = ref(null);
let sendEditCrfList = ref([]);
let groupFlowMenuType = ref(null);
let getTrialStatus = ref(localStorage.getItem('storageTrialStatus'));
/*
  0:添加，
  1:复用流程库的流程，
  2:添加至流程库，
  3:配置基准时间，
  4:配置暂停病例，
  5:编辑CRF
*/
const handleGroupFlowMenu = type => {
  groupFlowMenuType.value = type;
  const actions = {
    0: () => {
      sendEditCrfList.value = [];
      initPhase(0);
    },
    1: () => {
      store.commit('SET_TRIAL_MENU', { groupTab: 2 });
      router.push({
        path: '/processlibrary/processLibrary',
        query: { groupFlowType: 1, ...routerQuery.value },
      });
    },
    2: () => {
      initPhase(2);
    },
    5: () => {
      let editCrfForm = {
        isOpen: true,
        groupTab: 3,
        crfList: sendEditCrfList.value || [],
      };
      nextTick(() => {
        editCrfRef.value.open(editCrfForm);
      });
    },
  };

  // 执行对应的操作
  if (actions[type]) actions[type]();
};
const initPhase = type => {
  isPhaseAdd.value = true;
  // detail:true,为详情页，反之可编辑
  phaseOption.value.detail = false;
  // 将新增和清空按钮进行展示
  phaseOption.value.submitBtn = true;
  phaseOption.value.emptyBtn = true;
  for (const key in form.value) {
    form.value[key] = '';
  }
  phaseTitle.value = type === 0 ? '添加初诊或固定随诊阶段' : '新建流程';
  phaseAddDialogWidth.value = type === 0 ? 800 : 500;
  let options = {
    column: [
      {
        label: '流程名称',
        prop: 'name',
        type: 'input',
        span: 24,
        rules: [
          {
            required: true,
            message: '请输入流程名称',
            trigger: 'blur',
          },
        ],
      },
    ],
  };
  phaseOption.value = type === 0 ? getPhaseOption.value : options;
};
const changeCrfList = crfList => {
  sendEditCrfList.value = [...crfList];
  form.value.crfList = crfList.map(item => ({ crf: item.id }));
  console.log(form.value.crfList, sendEditCrfList.value);
};
// form表单提交按钮
const groupFlowSubmit = (form, done) => {
  if (groupFlowMenuType.value == 2) {
    form.groupId = routerQuery.value.groupId;
    addToProcessLibrary(form.groupId, form.name).then(res => {
      ElMessage({
        type: 'success',
        message: '操作成功!',
      });
      done();
      isPhaseAdd.value = false;
      initTreeWithCrf(getGroupId);
    });
  } else {
    initAdd(form, done);
  }
};
const initAdd = (form, done) => {
  form.trialId = routerQuery.value.trialId || null;
  form.groupId = routerQuery.value.groupId || null;
  form.type = routerQuery.value.isProcessLibrary ? '2' : '1';
  form.linkId = routerQuery.value.processLibraryId
    ? routerQuery.value.processLibraryId
    : routerQuery.value.groupId;
  if (form.id) {
    update(form).then(
      res => {
        ElMessage({
          type: 'success',
          message: '操作成功!',
        });
        done();
        isPhaseAdd.value = false;
        // 有processLibraryId就是CRF流程库入口进入的，反之就是从业务管理进入
        if (routerQuery.value.processLibraryId) {
          initProcessLibraryTreeWithCrf(routerQuery.value.processLibraryId);
        } else {
          initTreeWithCrf(getGroupId);
        }
      },
      error => {
        done();
      }
    );
  } else {
    add(form).then(
      res => {
        ElMessage({
          type: 'success',
          message: '操作成功!',
        });
        done();
        isPhaseAdd.value = false;
        // 有processLibraryId就是CRF流程库入口进入的，反之就是从业务管理进入
        if (routerQuery.value.processLibraryId) {
          initProcessLibraryTreeWithCrf(routerQuery.value.processLibraryId);
        } else {
          initTreeWithCrf(getGroupId);
        }
      },
      error => {
        done();
      }
    );
  }
};
const handleCrf = crfId => {
  store.commit('SET_TRIAL_MENU', { groupTab: 2 });
  router.push({
    path: '/scaleTemplate/formUse',
    query: { id: crfId },
  });
};
const initTreeWithCrf = async groupId => {
  if (groupId) {
    let res = await treeWithCrf(groupId);
    flowList.value = res.data.data;
    crfSelectOptions.value = flowList.value;
  }
};
const initProcessLibraryTreeWithCrf = async processLibraryId => {
  let res = await processLibraryTreeWithCrf(processLibraryId);
  flowList.value = res.data.data;
  crfSelectOptions.value = flowList.value;
};
/*
  type:1编辑，
  type:2删除
*/
const handleFlowCrf = type => {
  if (!crfSelect.value) {
    ElMessage({
      message: '请选择流程阶段',
      type: 'warning',
    });
    return;
  }
  const actions = {
    1: () => {
      getDetail(crfSelect.value).then(res => {
        sendEditCrfList.value = res.data.data.crfList;
        form.value = res.data.data;
      });
      initPhase(0);
    },
    2: () => {
      ElMessageBox.confirm('您确定要删除（同时删除子阶段）', '提 示', {
        confirmButtonText: '确 定',
        cancelButtonText: '取 消',
        type: 'warning',
      })
        .then(() => {
          remove(crfSelect.value).then(res => {
            ElMessage({
              type: 'success',
              message: '删除成功！',
            });
            crfSelect.value = '';
            // 有processLibraryId就是CRF流程库入口进入的，反之就是从业务管理进入
            if (routerQuery.value.processLibraryId) {
              initProcessLibraryTreeWithCrf(routerQuery.value.processLibraryId);
            } else {
              initTreeWithCrf(getGroupId);
            }
          });
        })
        .catch(() => {});
    },
    3: () => {
      getDetail(crfSelect.value).then(res => {
        sendEditCrfList.value = res.data.data.crfList;
        form.value = res.data.data;
        isPhaseAdd.value = true;
        phaseOption.value = getPhaseOption.value;
        // detail:true,为详情页，反之可编辑
        phaseOption.value.detail = true;
        // 将新增和清空按钮进行隐藏
        phaseOption.value.submitBtn = false;
        phaseOption.value.emptyBtn = false;
      });
    },
  };
  if (actions[type]) actions[type]();
};
onMounted(() => {
  if (getGroupId) {
    initTreeWithCrf(getGroupId);
  } else if (routerQuery.value.processLibraryId) {
    initProcessLibraryTreeWithCrf(routerQuery.value.processLibraryId);
  }
});
const changeGoBack = () => {
  emit('changeGoBack');
};
// 父级拖拽
const handleParentDragEnd = event => {
  let crfParentId = flowList.value.map(ele => ele.id).join(',');
  if (event.oldIndex != event.newIndex) {
    initPhaseCrfSort(crfParentId, 1);
  }
};

// 子集拖拽
const handleChildDragEnd = event => {
  // 获取被拖拽元素的 DOM 节点，并向上查找最近的父级容器
  const flowTextContent = event.item.closest('.flow-text-content');
  if (!flowTextContent) return;

  // 读取父级 ID
  const parentId = flowTextContent.dataset.parentId;

  // 查找父级在数组中的下标
  const parentIndex = flowList.value.findIndex(p => p.id === parentId);

  // 使用 parentIndex 进行后续操作
  let crfChildId = flowList.value[parentIndex].crfList.map(ele => ele.id).join(',');
  if (event.oldIndex != event.newIndex) {
    initPhaseCrfSort(crfChildId, 2);
  }
};
// 父子集拖拽所调用的接口方法
/*
TYPE 1：父级拖拽
TYPE 2：子集拖拽
*/
const initPhaseCrfSort = (ids, type) => {
  const requestMap = {
    1: phaseSort,
    2: phaseCrfSort,
    default: phaseSort,
  };
  const requestFunc = requestMap[type] || requestMap.default;
  requestFunc(ids).then(res => {
    initTreeWithCrf(getGroupId);
  });
};
</script>
<style scoped>
.group-flow-content {
  width: 90%;
  height: 100%;
}
.group-flow-content-process-library {
  margin: auto;
}
.edit-btn-content {
  padding: 10px 0;
}
.flow-content {
  width: 100%;
  height: calc(100% - 140px);
  background-color: #2c3b41;
}
.flow-title {
  width: 100%;
  color: #fff;
  display: flex;
  align-items: center;
  background-color: #1e282c;
}
.parent-container {
  width: 100%;
  /* height: 100%; */
  height: 95%;
  overflow-y: auto;
}
.flow-text-content {
  width: 100%;
  height: auto;
}
.lord-content {
  color: #fff;
  padding: 5px 10px;
  font-size: 14px;
  display: flex;
  align-items: center;
}
.seed-content {
  color: #afbdb4;
  padding: 5px 20px;
  font-size: 14px;
  display: flex;
  align-items: center;
}
.selcet-flow-content {
  width: 100%;
  height: auto;
  margin-bottom: 10px;
}
.select-title {
  font-size: 20px;
  color: black;
  font-weight: 550;
  margin-bottom: 5px;
}
.crf-list-content {
  width: 100%;
  height: auto;
  display: flex;
  flex-direction: column;
}
</style>
<template>
  <div
    class="group-flow-content"
    :class="routerQuery.isProcessLibrary ? 'group-flow-content-process-library' : ''"
  >
    <div class="edit-btn-content">
      <!-- <goBack @changeGoBack="changeGoBack" /> -->
      <el-button
        type="warning"
        plain
        :icon="ArrowLeftBold"
        @click="router.back()"
        v-if="routerQuery.isProcessLibrary"
        >返 回</el-button
      >
      <el-button
        type="primary"
        plain
        icon="el-icon-plus"
        @click="handleGroupFlowMenu(0)"
        v-if="
          routerQuery.isProcessLibrary == '1' ||
          (routerQuery.isProcessLibrary != '2' && getTrialStatus == '1')
        "
        >添 加</el-button
      >
      <!-- <el-button
        type="success"
        plain
        icon="el-icon-copy-document"
        @click="handleGroupFlowMenu(1)"
        v-if="routerQuery.isProcessLibrary != '2' && flowList.length === 0"
        >复用流程库的流程</el-button
      > -->
      <el-button
        type="success"
        plain
        icon="el-icon-copy-document"
        @click="handleGroupFlowMenu(1)"
        v-if="!routerQuery.isProcessLibrary && getTrialStatus == '1'"
        >复用流程库的流程</el-button
      >
      <el-button
        type="success"
        plain
        icon="el-icon-copy-document"
        @click="handleGroupFlowMenu(2)"
        v-if="!routerQuery.isProcessLibrary"
        >添加至流程库</el-button
      >
<!--      <el-button
        type="info"
        plain
        icon="el-icon-setting"
        @click="handleGroupFlowMenu(3)"
        v-if="!routerQuery.isProcessLibrary && getTrialStatus == '1'"
        >配置基准时间</el-button
      >
      <el-button
        type="info"
        plain
        icon="el-icon-setting"
        @click="handleGroupFlowMenu(4)"
        v-if="!routerQuery.isProcessLibrary && getTrialStatus == '1'"
        >配置暂停病例</el-button
      >-->
    </div>
    <div class="selcet-flow-content">
      <div class="select-title">选择流程阶段编辑</div>
      <el-select
        v-model="crfSelect"
        clearable
        filterable
        placeholder="请选择流程阶段"
        style="width: 240px; margin-right: 12px"
      >
        <el-option
          v-for="item in crfSelectOptions"
          :key="item.id"
          :label="item.title"
          :value="item.id"
        />
      </el-select>
      <!-- routerQuery.isProcessLibrary的值是从流程库入口进入的，!=2相当于在流程库新增和编辑的时候，才展示，isProcessLibrary1新增和编辑，2查看 -->
      <el-button
        type="primary"
        plain
        :icon="EditPen"
        @click="handleFlowCrf(1)"
        v-if="
          routerQuery.isProcessLibrary == '1' ||
          (routerQuery.isProcessLibrary != '2' && getTrialStatus == '1')
        "
        >编 辑</el-button
      >
      <el-button
        type="danger"
        plain
        :icon="CloseBold"
        @click="handleFlowCrf(2)"
        v-if="
          routerQuery.isProcessLibrary == '1' ||
          (routerQuery.isProcessLibrary != '2' && getTrialStatus == '1')
        "
        >删 除</el-button
      >
      <el-button
        type="primary"
        plain
        :icon="Search"
        @click="handleFlowCrf(3)"
        v-if="routerQuery.isProcessLibrary == '2' && getTrialStatus == '1'"
        >查 看</el-button
      >
    </div>
    <div class="flow-content">
      <div class="flow-title">
        <div class="flow-title" style="padding: 5px 10px">
          <Grid style="width: 16px; height: 16px; margin-right: 5px" />
          <span>{{ routerQuery.title }}</span>
        </div>
      </div>
      <!-- <div class="flow-text-content" v-for="(item, index) in flowList" :key="index">
        <div class="lord-content">
          <Fold style="width: 16px; height: 16px; margin-right: 5px" />
          <span>{{ item.label }}</span>
        </div>
        <div class="seed-content" v-for="(v, i) in item.children" :key="i">
          <Document style="width: 16px; height: 16px; margin-right: 5px" />
          <span>{{ v.value }}、{{ v.label }}</span>
        </div>
      </div> -->
      <draggable
        v-model="flowList"
        item-key="id"
        group="parents"
        @end="handleParentDragEnd"
        class="parent-container"
      >
        <template #item="{ element: parent }">
          <div class="flow-text-content" :data-parent-id="parent.id">
            <!-- 父级标题 -->
            <div class="lord-content" style="cursor: pointer">
              <Fold style="width: 16px; height: 16px; margin-right: 5px" />
              <span>{{ parent.title }}</span>
            </div>

            <!-- 内层子级拖拽 -->
            <draggable
              v-model="parent.crfList"
              item-key="id"
              :group="{ name: 'children', pull: false, put: ['children'] }"
              @end="handleChildDragEnd"
            >
              <template #item="{ element: child }">
                <div class="seed-content" style="cursor: pointer" @click="handleCrf(child.crf)">
                  <Document style="width: 16px; height: 16px; margin-right: 5px" />
                  <span>{{ child.crfName }}</span>
                </div>
              </template>
            </draggable>
          </div>
        </template>
      </draggable>
    </div>
    <el-dialog v-model="isPhaseAdd" :title="phaseTitle" :width="phaseAddDialogWidth">
      <avue-form :option="phaseOption" v-model="form" @submit="groupFlowSubmit">
        <template #crfList="{}">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            @click="handleGroupFlowMenu(5)"
            v-if="routerQuery.isProcessLibrary != '2'"
            >编辑CRF</el-button
          >
          <div class="crf-list-content">
            <span
              style="margin-bottom: 5px"
              v-for="(item, index) in sendEditCrfList"
              :key="index"
              >{{ item.name || item.crfName }}</span
            >
          </div>
        </template>
      </avue-form>
    </el-dialog>
    <editCrf ref="editCrfRef" @changeCrfList="changeCrfList" />
  </div>
</template>
